Page({
  data: {
    hiddenmodalput: true,
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    type: 0,
    icons: [],
    allIcons: [], // 保存所有习惯
    searchValue: '', // 搜索内容
    log: null,
    selectedStatus: 'b1', // 默认选中"完成"
    groupedHabits: {}, // 按场景分组的习惯
    currentHabit: null,
    selectedImage: null,
    // 使用与习惯页面相同的分类系统
    categories: [
      { id: 'morning', name: '起床' },
      { id: 'morning_routine', name: '晨间' },
      { id: 'noon', name: '中午' },
      { id: 'afternoon', name: '午间' },
      { id: 'evening', name: '晚间' },
      { id: 'before_sleep', name: '睡前' },
      { id: 'all_day', name: '全天' }
    ],
    categoryMapping: {
      'morning': '起床',
      'morning_routine': '晨间',
      'noon': '中午',
      'afternoon': '午间',
      'evening': '晚间',
      'before_sleep': '睡前',
      'all_day': '全天',
      'important': '重要习惯'
    },
    reverseCategoryMapping: {},
  },

  onLoad: function () {
    const reverseMapping = {};
    for (const key in this.data.categoryMapping) {
      reverseMapping[this.data.categoryMapping[key]] = key;
    }
    this.setData({
      reverseCategoryMapping: reverseMapping
    });

    // 获取用户信息
    const userId = wx.getStorageSync('userId');
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userId: userId,
      userInfo: userInfo
    });

    // 如果有用户ID，加载该用户的习惯列表
    if (userId) {
      this.data.icons = [];
      this.loadHabits(userId);
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  // 添加页面显示时的刷新逻辑
  onShow: function() {
    // 如果有用户ID，重新加载习惯列表
    if (this.data.userId) {
      this.loadHabits(this.data.userId);
    }
  },

  //渲染用户习惯数据
  loadHabits: function (userId) {
    wx.request({
      url: 'http://127.0.0.1:3001/getUserHabit',
      method: 'GET',
      data: {
        userId: userId
      },
      success: (res) => {
        const icons = res.data;
        // 确保数据更新到所有相关状态
        this.setData({
          icons: icons,
          allIcons: icons
        }, () => {
          // 在数据更新完成后重新分组
          this.groupHabitsByScenario(icons);
        });
      },
      fail: (err) => {
        console.error('获取用户习惯数据失败:', err);
      }
    });
  },

  // 按场景分组习惯
  groupHabitsByScenario: function(habits) {
    const grouped = {
      important: [],  // 确保初始化 important 数组
      other: []      // 确保初始化 other 数组
    };
    
    // 初始化所有分类
    for (const category of this.data.categories) {
      grouped[category.id] = [];
    }

    // 将习惯分配到对应场景
    habits.forEach(habit => {
      let addedToCategory = false;
      
      // 处理重要习惯
      if (habit.is_important === 1) {
        if (!grouped.important) {
          grouped.important = [];
        }
        grouped.important.push(habit);
        addedToCategory = true;
      }
      
      // 处理打卡情景
      if (habit.punch_in_scenarios) {
        const scenarios = habit.punch_in_scenarios.split(',').map(s => s.trim());
        scenarios.forEach(scenarioName => {
          const categoryId = this.data.reverseCategoryMapping[scenarioName];
          if (categoryId && grouped[categoryId]) {
            grouped[categoryId].push(habit);
            addedToCategory = true;
          }
        });
      }
      
      // 如果习惯没有被添加到任何特定情景分类，则将其添加到"其他"分类
      if (!addedToCategory) {
        grouped.other.push(habit);
      }
    });

    // 使用 setData 更新分组数据
    this.setData({
      groupedHabits: grouped
    });
  },

  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    });
  },

  //添加
  goAdd: function () {
    try {
    wx.navigateTo({
        url: '../../pages/habits_add/habits_add',
        success: function() { 
        },
        fail: function(err) {
          console.error('错误详情:', err);
        },
        complete: function() {
        }
    });
    getApp().globalData.page_type = 1;
    } catch (error) {
      console.error('执行跳转时发生错误:', error);
    }
  },
  //打卡
  record: function (e) {
    var id = e.currentTarget.id;
    const habit = this.data.icons.find(item => String(item.habit_id) == String(id));
    if (habit && (habit.is_finished == 1 || habit.is_finished === '1')) {
      wx.showToast({ title: '该习惯已结束，不能打卡', icon: 'none' });
      return;
    }
    if (habit && habit.isClockedInToday) {
      wx.showToast({ title: '今天已经打卡过了', icon: 'none' });
      return;
    }

    // 1. 固定天判断
    if (habit.habit_frequency_days) {
      let today = new Date();
      let weekDay = today.getDay(); // 0=周日, 1=周一...
      let dbWeekDay = weekDay === 0 ? 7 : weekDay;
      let allowedDays = habit.habit_frequency_days.split(',').map(Number);
      if (!allowedDays.includes(dbWeekDay)) {
        this.openClockInModal(habit);
        return;
      }
    }

    // 2. 每周/每月频次判断
    if (habit.habit_frequency_type == 2) {
      let now = new Date();
      let year = now.getFullYear();
      let week = getISOWeekNumber(now);
      wx.request({
        url: 'http://127.0.0.1:3001/getHabitWeekCount',
        data: {
          userId: this.data.userId,
          habitId: habit.habit_id,
          year: year,
          week: week
        },
        success: (res) => {
          if (res.data.count >= habit.habit_frequency_value) {
            this.openClockInModal(habit);
          }
        },
        fail: () => {
          wx.showToast({ title: '网络错误', icon: 'none' });
        }
      });
      return; // 等异步判断
    }

    // 针对每月频次的习惯
    if (habit.habit_frequency_type == 3) {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      wx.request({
        url: 'http://127.0.0.1:3001/getHabitMonthCount',
        data: {
          userId: this.data.userId,
          habitId: habit.habit_id,
          year: year,
          month: month
        },
        success: (res) => {
          const count = Number(res.data.count);
          const limit = Number(habit.habit_frequency_value);
          if (count >= limit) {
            this.openClockInModal(habit);
          }
        },
        fail: () => {
          wx.showToast({ title: '网络错误', icon: 'none' });
        }
      });
      return; // 等异步判断
    }

    // 其他类型习惯直接弹出打卡窗口
    this.openClockInModal(habit);
  },
  openClockInModal: function(habit) {
    this.setData({
      hiddenmodalput: false,
      currentHabit: habit,
      log: ''
    });
  },
  choose: function (e) {
    var id = e.target.id;
    this.setData({
      selectedStatus: id
    });
    if (id == 'b1') {
      getApp().globalData.updateid = 0;
    }
    if (id == 'b2') {
      getApp().globalData.deleteid = 0;
    }
  },
  //取消
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });

    getApp().globalData.updateid = 0;
    getApp().globalData.deleteid = 0;

  },
  //确认
  confirm: function () {
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let habit_id = this.data.currentHabit.habit_id;
    let user_id = this.data.userId;
    let logContent = this.data.log;
    // 找到当前习惯在 icons 数组中的索引
    const indexToUpdate = this.data.icons.findIndex(item => item.habit_id == habit_id);
    let num = 0;
    let newNum = 0;
    if (indexToUpdate !== -1) {
      num = this.data.icons[indexToUpdate].habit_num;
      // 计算新的天数
      let log_type = 1;
      newNum = num + 1;
      // 1. 直接更新习惯天数
      wx.request({
        url: 'http://127.0.0.1:3001/updateHabitNum',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          habit_id: parseInt(habit_id),
          habit_num: parseInt(newNum),
          user_id: String(user_id),
          isClockedInToday: 1
        },
        success: (res) => {
          if (res.data && (res.data.success === true || res.data.success === 'true')) {
            // 更新本地数据
            const updatedIcons = [...this.data.icons];
            updatedIcons[indexToUpdate].habit_num = newNum;
            updatedIcons[indexToUpdate].isClockedInToday = 1;
            this.setData({
              icons: updatedIcons,
              allIcons: updatedIcons
            });

            // 重新加载数据
            this.loadHabits(user_id);

            // 3. 打卡成功后，增加用户积分
            wx.request({
              url: 'http://127.0.0.1:3001/updateUserScore',
              method: 'POST',
              data: { userId: user_id, delta: 1 }, // 增加1点积分
              success: (scoreRes) => {
                if (scoreRes.data.success) { /* empty */ } else {
                  console.error('用户积分增加失败:', scoreRes.data.message);
                }
              },
              fail: (scoreErr) => {
                console.error('调用增加积分接口失败:', scoreErr);
              }
            });

            // 2. 无论有无日志内容或图片，都要插入日志
            if (this.data.selectedImage) {
              wx.uploadFile({
                url: 'http://127.0.0.1:3001/uploadAvatar',
                filePath: this.data.selectedImage,
                name: 'avatar',
                success: (uploadRes) => {
                  const data = JSON.parse(uploadRes.data);
                  if (data.success) {
                    this.saveLogWithImage(data.avatarUrl, log_type, year, month, day, user_id, habit_id, logContent, now);
                  } else {
                    wx.showToast({ title: '图片上传失败', icon: 'none' });
                  }
                }
              });
            } else {
              // 没有图片也要插入日志，内容允许为空
              this.saveLogWithImage('', log_type, year, month, day, user_id, habit_id, logContent || '', now);
            }

            // 3. 打卡成功后加1分
            wx.request({
              url: 'http://127.0.0.1:3001/updateUserScore',
              method: 'POST',
              data: {
                userId: this.data.userId,
                delta: 1
              },
              success: (res) => {
                if (res.data.success) { /* empty */ } else {
                  wx.showToast({ title: res.data.message, icon: 'none' });
                }
              },
              fail: (err) => {
                console.error('积分加分网络错误', err);
              }
            });
          } else {
            console.error('更新习惯天数失败:', res);
            wx.showToast({
              title: '更新失败，请重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('更新习惯天数失败:', err);
          wx.showToast({
            title: '更新失败，请重试',
            icon: 'none'
          });
        }
      });
    } else {
      console.error('未找到匹配的习惯:', habit_id);
      wx.showToast({
        title: '未找到习惯',
        icon: 'none'
      });
    }
  },
  saveLogWithImage: function (imageUrl, log_type, year, month, day, user_id, habit_id, logContent, now) {
    const localDate = new Date(now.getTime() + 8 * 60 * 60 * 1000);
    const log_CreatedTime = localDate.toISOString().slice(0, 19).replace('T', ' ');
    const requestData = {
      log_content: logContent || '',
      habit_id: habit_id,
      user_id: user_id,
      log_type: log_type,
      log_year: year,
      log_month: month,
      log_day: day,
      log_CreatedTime: log_CreatedTime,
      log_img: imageUrl
    };

    wx.request({
      url: 'http://127.0.0.1:3001/addLog',
      method: 'POST',
      data: requestData,
      success: (res) => {
        if (res.data.success) {
          wx.showToast({
            title: '打卡成功',
            icon: 'success'
          });
          this.loadHabits(this.data.userId);
          this.setData({
            hiddenmodalput: true,
            log: '',
            selectedImage: null
          });
          // 更新习惯页
          const pages = getCurrentPages();
          const habitsPage = pages.find(page => page.route === 'pages/habits/habits');
          if (habitsPage) {
            habitsPage.loadHabits(this.data.userId);
          }
        } else {
          wx.showToast({
            title: res.data.message || '日志添加失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('添加日志失败:', err);
        wx.showToast({
          title: '日志添加失败',
          icon: 'none'
        });
      }
    });
  },

  //日志
  log: function (res) {
    var content = res.detail.value;
    this.setData({
      log: content
    });
  },

  //搜索
  onSearchInput: function (e) {
    const value = e.detail.value.trim();
    this.setData({
      searchValue: value
    });

    if (!value) {
      // 没有输入，显示全部
      this.groupHabitsByScenario(this.data.allIcons);
    } else {
      // 过滤
      const filtered = this.data.allIcons.filter(item =>
        item.habit_name && item.habit_name.toLowerCase().indexOf(value.toLowerCase()) !== -1
      );
      this.groupHabitsByScenario(filtered);
    }
  },

  chooseImage: function() {
    wx.chooseImage({
      count: 1, // 最多可选几张
      sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
      success: (res) => {
        // 你可以 setData 到页面上显示，或上传到服务器
        this.setData({
          selectedImage: res.tempFilePaths[0]
        });
      }
    });
  },

  removeImage: function() {
    this.setData({
      selectedImage: null
    });
  },
});

// 获取当前日期是今年的第几周（周一为一周的开始）
function getISOWeekNumber(date) {
  const target = new Date(date.valueOf());
  // ISO week starts on Monday, so if Sunday (0), treat as 7
  const dayNr = (target.getDay() === 0 ? 7 : target.getDay());
  target.setDate(target.getDate() + 4 - dayNr);
  const yearStart = new Date(target.getFullYear(), 0, 1);
  const weekNo = Math.ceil((((target - yearStart) / 86400000) + 1) / 7);
  return weekNo;
}
